package com.wandian.cqcsk.mvvm.mine.daka;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.BitMapUtils;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.MyGlideEngine;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.ViewUtils;
import com.mylib.widget.CustomCoinToast;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.databinding.ActivityEveryDayDkBinding;
import com.wandian.cqcsk.dialog.MineDKTextDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.List;

import yanzhikai.textpath.painter.FireworksPainter;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;

import static com.mylib.libcore.config.AppConfig.CHOOSE_PHOTO;
import static com.mylib.libcore.config.AppConfig.PERMISSION_CODE;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 打卡
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_EVERYDAY_DK)
public class EveryDayDKActivity extends BaseMVVMActivity<EveryDayDKViewModel> implements  MineDKTextDialog.DialogViewClink {
    private ActivityEveryDayDkBinding dataBinding;
    private  String signPath="";
    private String sys_sign = "玩点";
    //看视频
    private TTRewardVideoAd mRewardVideoAd;
    private TTAdNative mTTAdNative;
    private boolean videoPrepare = false;
    //图片压缩地址
    private String compressImgPath;
    //文字
    private String upTitle = "--";
    private boolean isCW = true;//纯文-默认
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_every_day_dk);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initViewData();
        initClink();
        mViewModel.getTitleByTime();
        initCSJAD();
        defaultCW();
    }

    /**
     * 初始化穿山甲广告
     */
    private void initCSJAD(){
        try{
            TTAdManagerHolder.init(this);
            mTTAdNative = TTAdManagerHolder.getTTAdNative(this);
            mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("签到奖励",1,"sign"),
          //  mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("打卡奖励",1,"clock"),
                    new TTAdNative.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            videoPrepare = false;
                        }

                        @Override
                        public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                            videoPrepare = false;
                            if(UIUtils.isEmpty(ttRewardVideoAd)) return;
                            mRewardVideoAd = ttRewardVideoAd;
                       }

                        @Override
                        public void onRewardVideoCached() {
                            videoPrepare = true;
                        }
                    });
        }catch (Exception e){}
    }

    private void initViewData(){
        dataBinding.signature.setVisibility(View.GONE);
        mViewModel.appOpenContent.observe(this,text -> {
            if(!UIUtils.isEmpty(text)){
                if(UIUtils.isEmpty(mViewModel.formText)){
                    dataBinding.tvTitle.setText(text+"");
                }else dataBinding.tvTitle.setText(text+"\n"+"\n"+mViewModel.formText);
            }
        });

        mViewModel.oosBean.observe(this,oosBean->{
            if(!UIUtils.isEmpty(oosBean)){
                mViewModel.upLoadImg(this,oosBean,  compressImgPath,upTitle);
            }else mViewModel.saveDaKa("","",upTitle);
        });


        signPath = Environment.getExternalStorageDirectory().getPath() + "/SignPic/";
        File foder =new File(signPath);
        if (!foder.exists()) foder.mkdirs();
        //设置画笔颜色(可以不设置--默认画笔宽度10,画笔颜色黑,背景颜色白)
        dataBinding.signature.setPaintColor(Color.WHITE);
        dataBinding.signature.setPaintWidth(15);
        dataBinding.signature.setCanvasColor(Color.TRANSPARENT);
    }

    private void initClink(){
        //打卡
        dataBinding.tvDk.setOnClickListener(v -> {
            finishhideSoftBoard();
            dataBinding.tvDk.setVisibility(View.GONE);
            dataBinding.llDkSet.setVisibility(View.GONE);
            dataBinding.llDkColor.setVisibility(View.GONE);

            if(!UIUtils.isEmpty(dataBinding.tvTitle.getText())) upTitle = dataBinding.tvTitle.getText().toString();
            else upTitle ="--";

            if(isCW){
                prepareVideo();//准备视频播放
            }else {
                //压缩图片
                try {
                    Bitmap bitmap = ViewUtils.toBitmap(dataBinding.rlDkBg);
                    if(!UIUtils.isEmpty(bitmap)) compressImgPath = FileUtil.getCompressFilePath(bitmap);
                }catch (Exception e){}
                if(UIUtils.isOpenAD()){
                    prepareVideo();//准备视频播放
                }else {
                    if(!UIUtils.isEmpty(compressImgPath))mViewModel.getOOSToken();
                    else  mViewModel.saveDaKa("","",upTitle);
                }
            }


        });
        //清除签名
        dataBinding.tvDkCq.setOnClickListener(v ->{
            hindExit();
            clearSign();
            isCW = false;
            dataBinding.tvDkCq.setTextColor(getResources().getColor(R.color.sys_text_color));
            dataBinding.etDkSign.setText("");
        });
        //纯文
        dataBinding.tvDkCw.setOnClickListener(v -> defaultCW());

        //手写签名
        dataBinding.tvDkZq.setOnClickListener(v ->{
            hindExit();
            isCW = false;
            dataBinding.signature.setVisibility(View.VISIBLE);
            dataBinding.atpvAs.setVisibility(View.GONE);
            dataBinding.tvDkZq.setTextColor(getResources().getColor(R.color.sys_text_color));
        });
        //系统签名
        dataBinding.tvDkXq.setOnClickListener(v ->  {
            hindExit();
            isCW = false;
            dataBinding.llDkSign.setVisibility(View.VISIBLE);
            dataBinding.signature.setVisibility(View.GONE);
            dataBinding.tvDkXq.setTextColor(getResources().getColor(R.color.sys_text_color));
        });
        dataBinding.tvDkSignSave.setOnClickListener(v -> {
            isCW = false;
            if(UIUtils.isEmpty(dataBinding.etDkSign.getText()))return;
            sys_sign = dataBinding.etDkSign.getText().toString().trim();
            if(UIUtils.isEmpty(sys_sign)){
                ToastUtil.show("请输入签名文字");
                return;
            }
            hindExit();
            //文字绘制
            dataBinding.atpvAs.setVisibility(View.VISIBLE);
            dataBinding.atpvAs.setText(sys_sign);
            dataBinding.atpvAs.setPathPainter(new FireworksPainter());
            dataBinding.atpvAs.startAnimation(0, 1);
        });
        //修改文字
        dataBinding.tvDkText.setOnClickListener(v -> {
            hindExit();
            isCW = false;
            showEditTextDialog();
            dataBinding.tvDkText.setTextColor(getResources().getColor(R.color.sys_text_color));
        });
        //修改背景
        dataBinding.tvDkBg.setOnClickListener(v ->{
            hindExit();
            isCW = false;
            initCamera();
            dataBinding.tvDkBg.setTextColor(getResources().getColor(R.color.sys_text_color));
        });
        //修改文字颜色
        dataBinding.tvDkTextColor.setOnClickListener(v ->{
            hindExit();
            isCW = false;
            dataBinding.llDkColor.setVisibility(View.VISIBLE);
            dataBinding.tvDkTextColor.setTextColor(getResources().getColor(R.color.sys_text_color));

        });
        //其他空白
        dataBinding.rlDk.setOnClickListener(v ->  hindExit());
        //关闭
        dataBinding.toolBarIvBack.setOnClickListener(v ->  finish());
        //颜色点击事件
        dataBinding.viewColorBlack.setOnClickListener(v -> modifyTextColor( "black"));
        dataBinding.viewColorWhite.setOnClickListener(v -> modifyTextColor( "white"));
        dataBinding.viewColorYellow.setOnClickListener(v -> modifyTextColor( "yellow"));
        dataBinding.viewColorRed.setOnClickListener(v -> modifyTextColor( "red"));
        dataBinding.viewColorBlue.setOnClickListener(v -> modifyTextColor( "blue"));
        dataBinding.viewColorGreen.setOnClickListener(v -> modifyTextColor( "green"));
        dataBinding.viewColorSys.setOnClickListener(v -> modifyTextColor( "sys"));
        dataBinding.viewColorBlueLight.setOnClickListener(v -> modifyTextColor( "color_blue"));
    }

    //默认纯文
    private void defaultCW(){
        isCW = true;
        hindExit();
        clearSign();
        dataBinding.etDkSign.setText("");
        dataBinding.tvDkCw.setTextColor(getResources().getColor(R.color.sys_text_color));
    }


    /**
     * 准备视频
     */
    private void prepareVideo(){
        if (mRewardVideoAd != null && videoPrepare) {
            mRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                @Override
                public void onAdShow() {
                    Log.d("VideoAd","onAdShow");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd show", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdVideoBarClick() {
                    Log.d("VideoAd","onAdVideoBarClick");
                    //  Toast.makeText(RewardVideoActivity.this, "rewardVideoAd bar click", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdClose() {
                    Log.d("VideoAd","onAdClose");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd close", Toast.LENGTH_SHORT).show();
//                    CustomCoinToast.showToast(EveryDayDKActivity.this,"打卡奖励","1金币");
                    mRewardVideoAd = null;
                    if(isCW){
                        mViewModel.saveDaKa("","",upTitle);
                    }else {
                        if(!UIUtils.isEmpty(compressImgPath))mViewModel.getOOSToken();
                        else mViewModel.saveDaKa("","",upTitle);
                    }

                }

                @Override
                public void onVideoComplete() {
                    Log.d("VideoAd","onVideoComplete");
                    // Toast.makeText(RewardVideoActivity.this, "rewardVideoAd complete", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onVideoError() {
                    Log.d("VideoAd","onVideoError");
                }

                @Override
                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                }

                @Override
                public void onSkippedVideo() {
                    Log.d("VideoAd","onSkippedVideo");
                }
            });
            //展示广告，并传入广告展示的场景
            mRewardVideoAd.showRewardVideoAd(EveryDayDKActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
        } else {
            dataBinding.tvDk.setVisibility(View.VISIBLE);
            ToastUtil.show("视频资源准备中，请稍后再试");
            initCSJAD();
        }
    }

    private void hindExit(){
        finishhideSoftBoard();
        dataBinding.tvDkTextColor.setTextColor(getResources().getColor(R.color.white));
        dataBinding.tvDkBg.setTextColor(getResources().getColor(R.color.white));
        dataBinding.tvDkText.setTextColor(getResources().getColor(R.color.white));
        dataBinding.tvDkCq.setTextColor(getResources().getColor(R.color.white));
        dataBinding.tvDkXq.setTextColor(getResources().getColor(R.color.white));
        dataBinding.tvDkZq.setTextColor(getResources().getColor(R.color.white));
        dataBinding.atpvAs.setVisibility(View.GONE);
        dataBinding.signature.setVisibility(View.GONE);
        dataBinding.llDkColor.setVisibility(View.GONE);
        dataBinding.llDkSign.setVisibility(View.GONE);
    }

    //清除签名
    private void clearSign(){
        dataBinding.signature.clear();
        //设置画笔颜色(可以不设置--默认画笔宽度10,画笔颜色黑,背景颜色白)
        dataBinding.signature.setPaintColor(Color.BLACK);
        dataBinding.signature.setPaintWidth(16);
        dataBinding.signature.setCanvasColor(Color.WHITE);
    }
    //修改文字颜色
    private void modifyTextColor(String textColor){
        switch (textColor){
            case "black":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.black));
                break;
            case "white":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.white));
                break;
            case "yellow":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.yellow));
                break;
            case "red":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.red));
                break;
            case "blue":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.text_blue));
                break;
            case "green":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.text_green));
                break;
            case "sys":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.sys_text_color));
                break;
            case "color_blue":
                dataBinding.tvTitle.setTextColor(getResources().getColor(R.color.color_blue));
                break;
        }
    }

    //上传图片
    private void initCamera() {
        boolean isAllGranted = UIUtils.checkPermissionAllGranted(this,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS});
        if (isAllGranted) {
            choosePhoto();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS}, PERMISSION_CODE);
        }
    }

    //相册
    private void choosePhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage()) // 选择 图片 的类型
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .originalEnable(false)
                .maxOriginalSize(5)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                .theme(R.style.Matisse_Dracula)
                .capture(true) //是否提供拍照功能
                .autoHideToolbarOnSingleTap(true)
                .captureStrategy(new CaptureStrategy(true, mContext.getPackageName() + ".provider"))//存储到哪里
                .forResult(CHOOSE_PHOTO);// 设置作为标记的请求码
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                choosePhoto();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("requestCode",requestCode+"="+resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == CHOOSE_PHOTO) {
                if (!UIUtils.isEmpty(data)) {
                    List<Uri> mSelected = Matisse.obtainResult(data);
                    Bitmap bitmap = BitMapUtils.getBitmapFromUri(this, mSelected.get(0));
                    if(!UIUtils.isEmpty(bitmap))dataBinding.ivDkBg.setImageBitmap(bitmap);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        finishhideSoftBoard();
        if(mRewardVideoAd!= null) mRewardVideoAd = null;
        super.onDestroy();
    }

    //通用底部弹框
    private void showEditTextDialog(){
        try {
            MineDKTextDialog dialog = new MineDKTextDialog(EveryDayDKActivity.this, this::viewClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.rlDk)){
                dialog.showAtLocation(dataBinding.rlDk, Gravity.CENTER, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void viewClink(String text) {
        dataBinding.tvTitle.setText(text);
    }
}
